
var checkInterval = null;
var CHECK_SEARCH_INTERVAL = 5000;
var firstResult = true;
var searching = false;

function onLoad(q) {
  //start(q);
}

function query() {
  var q = $('q').value;
  start(q);
}

function start(q) {
  if (!q || q == '') return;
  if (searching) return;
  searching = true;
  $('status').innerHTML = ('Searching for <em>' + unescape(q) + '</em>');
  $('dots').innerHTML = '.';
  search(q);
  checkInterval = setInterval('checkSearch()',CHECK_SEARCH_INTERVAL);
}

// --------------------------------------------------
// Communication
// --------------------------------------------------

function search(q) {
  sendMsg('Search',"searchRest", { q:q});
}
function searchRest(res) {
  // no op
}

function stopSearch() {
  sendMsg('StopSearch',"stopSearchRest");
  clearInterval(checkInterval);
  searching = false;
  $('status').innerHTML = 'Stopped';
}
function stopSearchRest(res) {
  // no op
}

function checkSearch() {
  sendMsg('CheckSearch',"checkSearchRest");
  updateDots();

}
function checkSearchRest(res) {
  /*
   * res         := Parts | empty
   * Parts       := Part | Part '\t' Parts
   * Part        := MagnetLink '|' FileName
   * MagnetLink  := String
   * FileName    := String
   */
  if (firstResult) {
    $('status').innerHTML = '';
    firstResult = false;
  }
  var lines = res.split("\t");
  $('status').innerHTML = lines.length + ' results...';
  for (var i=0; i<lines.length; i++) {
    var line = lines[i];
    if (!line || line == "") continue;
    var parts = lines[i].split('|');
    var link = parts[0];
    var name = parts[1];
    var anonymize = false;
    // May not be defined
    try {
      var tmp = ANON;
      anonymize = tmp;
    } catch (e) {}
    if (anonymize) {
      var ps = name.split(' - ');
      if (ps.length > 1) {
        name = ps[0].gsub(/\w/,'*') + ps[1];
      }
    }
    var div = document.createElement("div");
    var a = document.createElement("a");
    div.appendChild(a);
    a.innerHTML = name;
    a.href = link;
    div.style.display = "none";
    $('searchResults').appendChild(div);
    Effect.SlideDown(div, { duration:.5 });
  }
}

// --------------------------------------------------
// Misc
// --------------------------------------------------

function updateDots() {
  var dots = $('dots').innerHTML;
  var newDots;
  if (dots == '.') {
    newDots = '..';
  } else if (dots == '..') {
    newDots = '...';
  } else {
    newDots = '.';
  }
  $('dots').innerHTML = newDots;
}
